package fun.stgoder.bmwf.core.domain;

import fun.stgoder.bmwf.core.constant.Constants;
import fun.stgoder.bmwf.core.exception.BaseException;
import lombok.Data;

import java.io.Serializable;

@Data
public class R<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    public static final int SUCCESS = Constants.SUCCESS;
    public static final int FAIL = Constants.FAIL;

    private int code;
    private String message;
    private T data;

    public static <T> R<T> ok() {
        return restResult(null, SUCCESS, null);
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, SUCCESS, null);
    }

    public static <T> R<T> ok(T data, String message) {
        return restResult(data, SUCCESS, message);
    }

    public static <T> R<T> fail() {
        return restResult(null, FAIL, null);
    }

    public static <T> R<T> fail(String message) {
        return restResult(null, FAIL, message);
    }

    public static <T> R<T> fail(T data) {
        return restResult(data, FAIL, null);
    }

    public static <T> R<T> fail(T data, String message) {
        return restResult(data, FAIL, message);
    }

    public static <T> R<T> fail(int code, String message) {
        return restResult(null, code, message);
    }

    private static <T> R<T> restResult(T data, int code, String message) {
        R<T> apiResult = new R<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMessage(message);
        return apiResult;
    }

    public void check() {
        if (Constants.SUCCESS.intValue() != code)
            throw new BaseException(code, message);
    }
}
